package com.yztc.xiami_app.ui.activity.user;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.liji.takephoto.TakePhoto;
import com.yztc.xiami_app.R;
import com.yztc.xiami_app.ui.user.presenter.IUserPresenter;
import com.yztc.xiami_app.ui.user.presenter.UserPresenterImpl;
import com.yztc.xiami_app.ui.user.view.IRegisterView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;


/**
 * "用户名、密码、邮箱注册"界面
 */
public class RegisterActivity extends AppCompatActivity implements IRegisterView {

    @BindView(R.id.imageview_back)
    ImageView backIv; //返回图标
    @BindView(R.id.userName_edt)
    EditText userNameEdt; //用户名
    @BindView(R.id.image_clean)
    ImageView cleanIv; //清除输入框
    @BindView(R.id.pwd_edt)
    EditText pwdEdt; //密码输入框
    @BindView(R.id.image_psw_show)
    ImageView pswShowIv; //是否显示密码
    @BindView(R.id.image_psw_clean)
    ImageView pswCleanIv;
    @BindView(R.id.pwd_confirm_edt)
    EditText confirmPwdEdt; //确认密码
    @BindView(R.id.image_psw_show2)
    ImageView pswShow2Iv;
    @BindView(R.id.image_psw_clean2)
    ImageView pswClean2Iv;
    @BindView(R.id.email_edt)
    EditText emailEdt; //邮箱
    @BindView(R.id.image_email_show)
    ImageView emailShowIv;
    @BindView(R.id.image_email_clean)
    ImageView emailCleanIv;
    @BindView(R.id.register_btn)
    Button registerBtn; //注册
    @BindView(R.id.user_header_pic_iv)
    ImageView userHeaderPicIv; //用户头像
    @BindView(R.id.select_header_pic_btn)
    Button selectHeaderPicBtn; //选择头像按钮
    @BindView(R.id.phone_edt)
    EditText phoneEdt; //手机号码

    private boolean flag;
    private Context mContext;
    private IUserPresenter mUserPresenter;
    private BmobFile userHeaderFile; //用户头像在Bmob云中存储的文件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initView();
        mContext = this;
        mUserPresenter = new UserPresenterImpl(this);
    }
    private void initView() {
        userNameEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String name = userNameEdt.getEditableText() + "";
                if(!TextUtils.isEmpty(name)){
                    cleanIv.setVisibility(View.VISIBLE);
                }else{
                    cleanIv.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        pwdEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pwd =pwdEdt .getEditableText() + "";
                if(!TextUtils.isEmpty(pwd)){
                    pswCleanIv.setVisibility(View.VISIBLE);
                }else{
                    pswCleanIv.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        confirmPwdEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String confirmPwd =confirmPwdEdt .getEditableText() + "";
                if(!TextUtils.isEmpty(confirmPwd)){
                    pswClean2Iv.setVisibility(View.VISIBLE);
                }else{
                    pswClean2Iv.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        emailEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String email =emailEdt .getEditableText() + "";
                if(!TextUtils.isEmpty(email)){
                    emailCleanIv.setVisibility(View.VISIBLE);
                }else{
                    emailCleanIv.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
    //注册
    @OnClick({R.id.select_header_pic_btn, R.id.register_btn, R.id.imageview_back,R.id.image_clean,
            R.id.image_psw_clean,R.id.image_psw_clean2,R.id.image_email_clean,R.id.image_psw_show,
            R.id.image_psw_show2,R.id.image_email_show})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.select_header_pic_btn:
                //选择用户头像
                selectHeaderPic();
                break;
            case R.id.register_btn:
                //注册
                register();
                break;
            case R.id.imageview_back:
                finish(); //关闭当前页面
                break;
            case R.id.image_clean:
                userNameEdt.setText("");
                break;
            case R.id.image_psw_clean:
                pwdEdt.setText("");
                break;
            case R.id.image_psw_clean2:
                confirmPwdEdt.setText("");
                break;
            case R.id.image_email_clean:
                emailEdt.setText("");
                break;
            case R.id.image_psw_show:
                flag=!flag;
                setPassworldIsVisible(flag,pwdEdt,pswShowIv);
                break;
            case R.id.image_psw_show2:
                flag=!flag;
                setPassworldIsVisible(flag,confirmPwdEdt,pswShow2Iv);
                break;
            case R.id.image_email_show:
                flag=!flag;
                setPassworldIsVisible(flag,emailEdt,emailShowIv);
                break;
        }
    }
    //输入框密码是否可见
    private void setPassworldIsVisible(boolean flag, EditText pswEdt,ImageView showIv) {
        if (flag) { //可见
            showIv.setImageResource(R.mipmap.switch_in_show);
            pswEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            showIv.setImageResource(R.mipmap.switch_in_hide);
            pswEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        //切换后将EditText光标置于末尾
        CharSequence charSequence = pswEdt.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }
    //用户选择头像
    private void selectHeaderPic() {
        //用户头像
        final TakePhoto takePhoto = new TakePhoto(mContext);
        takePhoto.setOnPictureSelected(new TakePhoto.onPictureSelected() {
            @Override
            public void select(String path) {
                //获取到的选择后的（无论是否剪裁），只要选择了照片，并点击了"确定"的按钮之后
                //就会回调此方法，并回传图片的路径
                //显示保存图片
                showAndSaveUserHeaderPic(path);
            }
        });
        //显示选择的PopUpWindow
        takePhoto.show();
    }

    //显示并保存用户头像
    private void showAndSaveUserHeaderPic(String path) {

        //显示用户头像
        Glide.with(mContext).load("file://" + path)
                .asBitmap()
                .fitCenter()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                        roundedBitmapDrawable.setCircular(true); //设置圆形图片
                        userHeaderPicIv.setImageDrawable(roundedBitmapDrawable);
                    }
                });
        //保存用户头像到Bmob云的文件管理中
        mUserPresenter.saveHeaderPic(path);
    }

    //注册
    private void register() {
        String userName = userNameEdt.getText().toString(); //用户名
        String psd = pwdEdt.getText().toString(); //密码
        String confirmPsd = confirmPwdEdt.getText().toString(); //确认密码
        String email = emailEdt.getText().toString(); //邮箱
        String phone = phoneEdt.getText().toString(); //手机号码

        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(psd) || TextUtils.isEmpty(confirmPsd)) {
            return;
        }
        //在Bmob云中注册用户的个人资料
        mUserPresenter.register(userName, confirmPsd, email,phone, userHeaderFile);
    }

    //对用户注册结果的处理
    @Override
    public void registerResult(boolean isSuccess, int errorCode) {
        if (isSuccess) {
            //注册成功
            Toast.makeText(mContext, "注册成功", Toast.LENGTH_SHORT).show();
            finish(); //关闭当前页面
        } else {
            if (errorCode == 203) {
                //邮箱已存在
                Toast.makeText(mContext, "邮箱已存在", Toast.LENGTH_SHORT).show();
            } else {
                //注册失败
                Toast.makeText(mContext, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 上传头像成功
     *
     * @param bmobFile Bmob云中保存的用户的头像的文件
     */
    @Override
    public void uploadSuccess(BmobFile bmobFile) {
        Toast.makeText(mContext, "上传头像成功", Toast.LENGTH_SHORT).show();
        userHeaderFile = bmobFile;
    }

    //上传头像失败
    @Override
    public void uploadFailure() {
        Toast.makeText(mContext, "上传头像失败", Toast.LENGTH_SHORT).show();
    }
}
